//
//  RecAudioListViewController.swift
//

import UIKit
import Alamofire

class RecAudioListViewController: BaseViewController {

    var id: String = ""
    var atype: String = ""
    var outerid: String = ""
    private var page: Int = 1
    private var dataSource = [AudioItemModel]()
    private var audioModel = AudioModel()
    
    private lazy var headerView: RecAudioHeaderView = {
        RecAudioHeaderView()
    }()
    
    private lazy var tableView: UITableView = {
        let view = UITableView(frame: .zero, style: .plain)
        view.separator(left: space, right: 0)
        view.plainFooterView()
        view.rowHeight = 55.fit
        view.delegate = self
        view.dataSource = self
        view.register(cellWithClass: RecAudioListCell.self)
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        addSubviews()
    }

    private func addSubviews() {
        disablesAdjustScrollViewInsets(tableView)
        view.addSubview(headerView)
        view.addSubview(tableView)
        
        let height = (UIScreen.width) / 3
        headerView.snp.makeConstraints { (make) in
            make.top.equalTo(topLayoutGuideBottom)
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.height.equalTo(height)
        }
        
        tableView.snp.makeConstraints { (make) in
            make.top.equalTo(headerView.snp.bottom)
            make.left.right.equalToSuperview()
            make.bottom.equalTo(safeAreaLayoutGuideBottom)
        }
        
        tableView.mj_headerRefresh { [weak self] in
            guard let `self` = self else { return }
            self.page = 1
            if self.atype == "2" {
                self.requestData()
            } else {
                self.requestData()
                self.requestAudioList()
            }
        }
        
        tableView.mj_footerRefresh { [weak self] in
            guard let `self` = self else { return }
            self.page += 1
            if self.atype == "2" {
                self.requestData()
            } else {
                self.requestAudioList()
            }
        }
        
        tableView.beginRefreshing()
    }

    private func refreshSeletedData() {
        let item = AudioPlayerViewController.share.playerItemModel
        dataSource = dataSource.map { model -> AudioItemModel in
            var m = model
            if m.id == item.id {
                m.isSelected = true
            } else {
                m.isSelected = false
            }
            return m
        }
        tableView.reloadData()
    }
}

extension RecAudioListViewController {
    
    private func requestData() {
        Network.Rec
            .audioAlbum(id: id, page: page)
            .request()
            .responseData(AudioModel.self) { [weak self] (model) in
                guard let `self` = self else { return }
                self.tableView.endFooterRefresh()
                self.headerView.update(model.result.album)
                self.audioModel = model.result
                if self.atype == "2" {
                    if self.tableView.isHeaderRefresh {
                        self.dataSource.removeAll()
                    }
                    self.tableView.endHeaderRefresh()
                    self.dataSource.append(contentsOf: model.result.items)
                    self.refreshSeletedData()
                }
        } failure: { [weak self] (error) in
            guard let `self` = self else { return }
            self.tableView.endHeaderRefresh()
            self.tableView.endFooterRefresh()
            Toast.show(info: error.errorMessage)
        }
    }
    
    private func requestAudioList() {
        Network.Rec
            .audioList(id: outerid, page: page)
            .request()
            .responseAudioData([AudioItemModel].self) { [weak self] (model) in
                guard let `self` = self else { return }
                if self.tableView.isHeaderRefresh {
                    self.dataSource.removeAll()
                }
                self.tableView.endHeaderRefresh()
                self.tableView.endFooterRefresh()
                self.dataSource.append(contentsOf: model.data)
                self.refreshSeletedData()
        } failure: { [weak self] (error) in
            guard let `self` = self else { return }
            self.tableView.endHeaderRefresh()
            self.tableView.endFooterRefresh()
            Toast.show(info: error.errorMessage)
        }
    }
}

extension RecAudioListViewController: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withClass: RecAudioListCell.self)
        cell.countLabel.text = "\(indexPath.row + 1)"
        cell.update(dataSource[indexPath.row])
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let vc = AudioPlayerViewController.share
        vc.atype = atype
        vc.audioModel = audioModel
        vc.dataSource = dataSource
        vc.playerIndex = indexPath.row
        vc.didAudioItemModeChange = { [weak self] in
            guard let `self` = self else { return }
            self.refreshSeletedData()
        }
        vc.playerURL()
        push(vc)
    }
}
